package com.bachongLightNovel.message.task;

import com.alibaba.fastjson2.JSON;
import com.bachongLightNovel.message.mapper.MessageMapper;
import com.bachongLightNovel.message.socket.WebSocketServer;
import com.bachongLightNovel.model.pojo.message.Message;
import com.bachongLightNovel.model.vo.message.MessageVo;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 * @author vermouth
 */

@Component
public class MessageTask {

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private MessageMapper messageMapper;

    @Scheduled(cron = "0/5 * * * * ?")
    @Transactional
    public void sendMessage(){
        //查询所有的未读消息
        List<Message> messageList=messageMapper.selectByRead((short) 0);
        //遍历消息消息，发送到相应的客户端
        for (Message message : messageList) {
            Long targetId = message.getTargetId();
            //查看要发送的对方是否在线
            if (WebSocketServer.sessionPools.containsKey(targetId)){
                try {
                    Session session = WebSocketServer.sessionPools.get(targetId);
                    //封装成要求的格式
                    MessageVo vo = new MessageVo();
                    vo.setType(message.getType());
                    vo.setContent(message.getContent());
                    String json = JSON.toJSONString(vo);
                    session.getBasicRemote().sendText(json);
                    messageMapper.updateReadById((short) 1,message.getId());
                } catch (IOException e) {
                    throw new RuntimeException();
                }
            }
        }
    }
}
